package excel

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"sync"

	"github.com/xuri/excelize/v2"
)

const (
	HOST           = "https://syapi.sytechnology.com"
	TOKEN          = "ba31670f-87ca-4c9a-a4aa-4db5d45845f2"
	FileName       = "file3.xlsx"
	SheetName      = "Sheet1"
	HeaderRowIndex = 1
)

type Record struct {
	FilePhysicalID string
	CustomerName   string
	ContractNumber string
	FileName       string
}

func ReadExcel() []Record {
	f, err := excelize.OpenFile("../" + FileName)
	if err != nil {
		log.Fatalf("无法打开文件: %v", err)
	}
	defer f.Close()

	rows, err := f.GetRows(SheetName)
	if err != nil {
		log.Fatalf("无法获取行: %v", err)
	}

	colIndices := map[string]int{
		"文件物理ID": -1,
		"客户名称":   -1,
		"合同编号":   -1,
		"文件名称":   -1,
	}
	for colIndex, colCell := range rows[HeaderRowIndex-1] {
		if _, ok := colIndices[colCell]; ok {
			colIndices[colCell] = colIndex
		}
	}

	var records []Record
	for _, row := range rows[HeaderRowIndex:] {
		filePhysicalID := getCellValue(row, colIndices["文件物理ID"])
		if filePhysicalID != "" {
			record := Record{
				FilePhysicalID: filePhysicalID,
				CustomerName:   getCellValue(row, colIndices["客户名称"]),
				ContractNumber: getCellValue(row, colIndices["合同编号"]),
				FileName:       getCellValue(row, colIndices["文件名称"]),
			}
			records = append(records, record)
		}
	}

	return records
}

func cleanString(str string) string {
	return strings.TrimSpace(str)
}

func WriteFile(list []Record, wg *sync.WaitGroup) {
	outputDir := "../pdf"

	// 确保输出目录存在
	if err := os.MkdirAll(outputDir, os.ModePerm); err != nil {
		fmt.Println("Error creating directories:", err)
		return
	}

	for _, item := range list {
		wg.Add(1)
		go func(item Record) {
			defer wg.Done()

			outputFilename := fmt.Sprintf("%s-%s-%s", cleanString(item.CustomerName), cleanString(item.ContractNumber), cleanString(item.FileName))
			outputPath := filepath.Join(outputDir, outputFilename)

			// 检查文件是否已经存在且大小大于0
			if fileInfo, err := os.Stat(outputPath); err == nil && fileInfo.Size() > 0 {
				fmt.Printf("File %s already exists and is not empty, skipping download.\n", outputPath)
				return // 文件存在且非空，跳过当前循环，不再下载
			}

			// 下载文件的函数
			downloadFile := func(url, outputPath string) error {
				// 发送GET请求
				resp, err := http.Get(url)
				if err != nil {
					return fmt.Errorf("error while downloading file: %v", err)
				}
				defer resp.Body.Close()

				// 检查HTTP响应状态
				if resp.StatusCode != http.StatusOK {
					return fmt.Errorf("server returned non-200 status: %d %s", resp.StatusCode, resp.Status)
				}

				// 创建文件
				outFile, err := os.Create(outputPath)
				if err != nil {
					return fmt.Errorf("error while creating file: %v", err)
				}
				defer outFile.Close()

				// 将响应流复制到文件
				_, err = io.Copy(outFile, resp.Body)
				if err != nil {
					return fmt.Errorf("error while copying file: %v", err)
				}
				return nil
			}

			filePhysicalID := cleanString(item.FilePhysicalID)
			url := fmt.Sprintf("%s/file/getFile/%s?access_token=%s", HOST, filePhysicalID, TOKEN)

			// 尝试下载文件
			if err := downloadFile(url, outputPath); err != nil {
				fmt.Println(err)
				// 如果下载失败或文件大小为0，则尝试重新下载
				if fileInfo, err := os.Stat(outputPath); os.IsNotExist(err) || fileInfo.Size() == 0 {
					fmt.Printf("Attempting to re-download file %s\n", outputPath)
					if err := downloadFile(url, outputPath); err != nil {
						fmt.Println("Failed to download file on retry:", err)
						return
					}
				}
			}

			fmt.Printf("File %s downloaded successfully to %s\n", item.FilePhysicalID, outputPath)
		}(item)
	}
}

func getCellValue(row []string, index int) string {
	if index >= 0 && index < len(row) {
		return row[index]
	}
	return ""
}
